package cn.org.timespace.easyframe.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 用于读取资源配置文件
 * 
 * @author 陈灿
 */
public class EfResourceContext {

	public static final Log log = LogFactory.getLog(EfResourceContext.class);

	private Map<String, String> globalMap = new HashMap<String, String>();
	private static EfResourceContext efResourceContext = null;
	private static boolean reload = true;

	private EfResourceContext() {
		
		if(log.isInfoEnabled()) log.info("正在加载properties配置文件...");
		
		List<String> propList = new ArrayList<String>();
		propList.add("tsons.properties");
		propList.add("tsSql.properties");
		
		if(log.isInfoEnabled()) log.info("加载的配置文件有：<"+propList+">");
		
		for(String one : propList){
			loadByStream(one);
		}
	}

	public static EfResourceContext getInstance() {
		
		if(efResourceContext != null){
			if (reload){
				if(log.isInfoEnabled()) log.info("重新加载配置文件...");
				efResourceContext = new EfResourceContext();
			}
		}
		
		if (efResourceContext == null){
			if(log.isInfoEnabled()) log.info("第一次加载配置文件...");
			efResourceContext = new EfResourceContext();
		}

		return efResourceContext;
	}

	public String getParamValue(String key) {
		String o = globalMap.get(key);
		if (o != null) {
			return o.toString();
		} else {
			return null;
		}
	}

	@SuppressWarnings("unused")
	private void load(String file) {
		ResourceBundle rb = ResourceBundle.getBundle(file);
		String key;
		Enumeration<String> e = rb.getKeys();
		while(e.hasMoreElements()){
			key = (String) e.nextElement();
			globalMap.put(key, rb.getObject(key).toString());
		}
	}

	private void loadByStream( String fileName) {
		Properties p = new Properties();
		String key;
		
		try {
			java.io.InputStream in = getClass().getClassLoader().getResourceAsStream(fileName);
			p.load(in);
			Enumeration<Object> e = p.keys();
			while(e.hasMoreElements()){
				key = (String) e.nextElement();
				globalMap.put(key, p.getProperty(key));
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}